<?php

namespace app\index\controller;
use app\BaseController;
use GuzzleHttp\Client;
use OSS\Model\ServerSideEncryptionConfig;
use OSS\Core\OssException;

class Other extends BaseController
{
    public function archives() {
        $client = new Client([
            'verify' => false
        ]);
        $page = $this->request->get('page');
        $result = $client->request('GET','https://coserlab.io/wp-json/wp/v2/posts?categories=5&per_page=10&page='.$page);
        $result = json_decode($result->getBody()->getContents(),true);
        foreach ($result as $key => $item) {
            $this->saveImg($item, $page.'-'.$key.'-');
        }
    }
    private function saveImg($item, $append) {
        $folderPath = "fengmao/".$append.$item['title']['rendered'];
        $fullFolderPath = public_path($folderPath);
        if (!file_exists($fullFolderPath)) {
            mkdir($fullFolderPath, 0777, true);
        }
        //  保存图片到文件夹
        foreach ($item['ncThumbnails'] as $key => $val) {
            $fileName = basename($val);
            $savePath =$folderPath.'/'.$fileName;
            //  判断文件是否存在
            if (file_exists($savePath)) {
                continue;
            }
            // 判断图片链接是否有效
            $headers = get_headers($val);
            if (strpos($headers[0], '200') === false) {
                echo $val. '已失效';
                echo '<br>';
                continue;
            }
            file_put_contents($savePath, file_get_contents($val));
        }
        echo $folderPath. '已完成';
        echo '<br>';
    }

//    public function ossUpload() {
//        $file = request()->file('file');
//        if (!$file) {
//            return result()->fail('请选择要上传的文件', 400);
//        }
//        $ossClient = new \OSS\OssClient(config('oss.accessKeyId'), config('oss.accessKeySecret'), config('oss.endpoint'));
//        $bucket = config('oss.bucket');
//        $object = 'uploads/' . date('Ymd') . '/' . uniqid() . '.' . $file->extension();
//        $ossClient->uploadFile($bucket, $object, $file->getRealPath());
//        $url = 'https://' . $bucket . '.' . config('oss.endpoint') . '/' . $object;
//        return result()->success([
//            'url' => $url
//        ]);
//    }
}